package com.fsgom.search.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.fsgom.common.layout.FrontLayout;
import com.fsgom.common.layout.LayoutName;
import com.fsgom.common.web.layout.annotations.Layout;
import com.fsgom.common.web.layout.annotations.LayoutConfigure;
import com.fsgom.common.layout.element.GlobalLayoutElement;
import com.fsgom.search.bean.NaverSearchShoppingParam;

@Controller
@RequestMapping("/search")
public class NaverSearchShoppingController {

	static final String NV_API_AUTH_KEY = "51af92d0c715ae6afb642e2964ae79da";
	
	private final Logger log = Logger.getLogger(NaverSearchShoppingController.class);
	
	@LayoutConfigure
	public void setupLayout(FrontLayout layoutConfig, Map<String, Object> params) {
		//layoutConfig.getElement(GlobalLayoutElement.class).addCssPrefix(null);
		//layoutConfig.getElement(GlobalLayoutElement.class).addJsPrefix(null);
		layoutConfig.getElement(GlobalLayoutElement.class).setTitlePrefix("쇼핑검색");
		layoutConfig.getElement(GlobalLayoutElement.class).setTitlePostfix("사육곰");
	}
	
	@Layout(value = LayoutName.XML)
	@RequestMapping("/shopping")
	public String nvApiSearch(HttpServletRequest request, ModelMap modelMap, @ModelAttribute("params") NaverSearchShoppingParam params) {
		URL url = null;
		URLConnection conn = null;
		HttpURLConnection urlConn = null;
		BufferedReader in = null;
		
		try {
			url = new URL("http://openapi.naver.com/search" + params.getParams());
			conn = url.openConnection();
			urlConn = (HttpURLConnection) conn;
			urlConn.setRequestMethod("GET");
			urlConn.setDoOutput(true);
			urlConn.setDoInput(true);
			urlConn.setUseCaches(false);
			urlConn.setDefaultUseCaches(false);
//			PrintWriter out = new PrintWriter(urlConn.getOutputStream());
//			out.println(params.getParams());
//			out.close();
			log.info("##params : " + params.getParams());
			in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
			String inputLine = null;
			StringBuilder sb = new StringBuilder();
			while ((inputLine = in.readLine()) != null) {
				log.info("## msg : " + inputLine);
				sb.append(inputLine);
			}
			String result = sb.toString();
			modelMap.put("result", result);
		} catch (UnsupportedEncodingException e) {
			log.error(e.getMessage(), e);
		} catch (MalformedURLException e) {
			log.error(e.getMessage(), e);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		} finally {
			try {
				if (in != null) {
					in.close();
				}
				if (url != null) {
					url = null;
				}
				if (conn != null) {
					conn = null;
				}
				if (urlConn != null) {
					urlConn.disconnect();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return "/search/nv_shopping";
	}
	
	@Layout(value = LayoutName.XML)
	@RequestMapping("/makeXml")
	public String nvApiSearchForXml(HttpServletRequest request, ModelMap modelMap) {
		URL url = null;
		URLConnection conn = null;
		HttpURLConnection urlConn = null;
		BufferedReader in = null;
		String apiUrl = "http://openapi.naver.com/search?key=" + NV_API_AUTH_KEY + "&target=shop&display=1000&sort=date&query=";
		try {
			url = new URL("http://openapi.naver.com/search");
			conn = url.openConnection();
			urlConn = (HttpURLConnection) conn;
			urlConn.setRequestMethod("GET");
			urlConn.setDoOutput(true);
			urlConn.setDoInput(true);
			urlConn.setUseCaches(false);
			urlConn.setDefaultUseCaches(false);
//			PrintWriter out = new PrintWriter(urlConn.getOutputStream());
//			out.println(params.getParams());
//			out.close();
			in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
			String inputLine = null;
			StringBuilder sb = new StringBuilder();
			while ((inputLine = in.readLine()) != null) {
				log.info("## msg : " + inputLine);
				sb.append(inputLine);
			}
			String result = sb.toString();
			modelMap.put("result", result);
		} catch (UnsupportedEncodingException e) {
			log.error(e.getMessage(), e);
		} catch (MalformedURLException e) {
			log.error(e.getMessage(), e);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		} finally {
			try {
				if (in != null) {
					in.close();
				}
				if (url != null) {
					url = null;
				}
				if (conn != null) {
					conn = null;
				}
				if (urlConn != null) {
					urlConn.disconnect();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return "/search/nv_shopping";
	}
}
